package cn.cnsy123.blog.application.controller;

import cn.cnsy123.blog.application.http.base.BaseResponse;
import cn.cnsy123.blog.application.http.request.UserRegisterRequest;
import cn.cnsy123.blog.application.http.response.UserRegisterResponse;
import cn.cnsy123.blog.application.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;

/**
 * @author yangpengfei
 * @description 博客客户端-用户注册API
 * @date 2019-10-13 17-47-21
 */
@RestController
public class UserRegisterController {

    private static final Logger logger = LoggerFactory.getLogger(UserRegisterController.class);

    @Autowired
    private UserInfoService userInfoService;

    @PostMapping(value = "/user/register")
    public BaseResponse<UserRegisterResponse> registerUser(@Valid  @RequestBody UserRegisterRequest userRegisterRequest, BindingResult result){
        BaseResponse<UserRegisterResponse> response = new BaseResponse<UserRegisterResponse>();
        response.setCode("0000");
        response.setMessage("系统请求成功");
        response.setRequestTime(new Date(System.currentTimeMillis()));
        logger.debug("博客客户端-用户注册API-请求参数",userRegisterRequest);

        if(result.hasErrors()){
            response.setData(new UserRegisterResponse("1003",result.getAllErrors().get(0).getDefaultMessage()));
            response.setResponseTime(new Date(System.currentTimeMillis()));
            return response;
        }
        UserRegisterResponse userRegisterResponse = null;
        try {
            userRegisterResponse = userInfoService.saveUserInfo(userRegisterRequest);
        }catch(Exception e){
            logger.error("注册用户失败",e);
            userRegisterResponse = new UserRegisterResponse("1099","注册失败，服务异常，请稍后重试");
        }
        response.setData(userRegisterResponse);
        response.setResponseTime(new Date(System.currentTimeMillis()));
        return response;
    }
}
